package com.hbnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.WorkMapper;
import com.hbnu.system.mapper.WorkqualificationMapper;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.dto.WorkDTO;
import com.hbnu.system.model.entity.*;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.CheckRoleUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

@Service
public class WorkQualificationServiceImpl extends ServiceImpl<WorkqualificationMapper, Work_Qualification> implements IWorkQualificationService {
    @Autowired
    private IWorkService iWorkService;

    @Autowired
    private IWorkQualificationService iWorkQualificationService;

    @Autowired
    private IWorkPressSerivce iWorkPressSerivce;

    @Autowired
    private IWorkTypeSerivce iWorkTypeSerivce;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IWorkauthorService iWorkauthorService;

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");


    /**
     * 添加
     * @param workQualification
     * @return
     */
    @Override
    public boolean addWork_Qualification(Work_Qualification workQualification) {

        // 1. 基础校验
        Work work = iWorkService.getWork(workQualification.getWorkID());
        checkRoleUtil.checkPermissionProject(work.getStatus());

        WorkDTO workDTO = iWorkService.getWorkDTOById(workQualification.getWorkID());
        if (Objects.isNull(workDTO)) {
            throw new BaseException("著作编号有误!");
        }
        if (existQuantification(workQualification.getWorkID())) {
            throw new BaseException("该著作已存在量化数据，无法重复添加!");
        }

        double finalScore;

        if(workQualification.getManualScoreMode()== "true"){
            workQualification.setFinalValue(workQualification.getFinalValue());
            workQualification.setNote(workQualification.getNote());
            finalScore = workQualification.getFinalValue();
        }else{
            // 3. 查询类型系数（含获奖情况）
            QueryWrapper<Work_Type> typeQuery = Wrappers.query();
            typeQuery.eq("Type1ID", workQualification.getType1ID())
                    .eq("Type2ID", workQualification.getType2ID());

            Work_Type workType = iWorkTypeSerivce.getOne(typeQuery);
            if (Objects.isNull(workType)) {
                throw new BaseException("未找到匹配的著作类型配置!");
            }

            // 4. 查询出版社系数
            Work_press workPress = iWorkPressSerivce.getOne(Wrappers.lambdaQuery(Work_press.class)
                    .eq(Work_press::getPressLevel, workQualification.getPressLevel()));
            if (Objects.isNull(workPress)) {
                throw new BaseException("未找到匹配的出版社配置!");
            }


            // 5. 计算基础分值（未乘合作权重）
            double baseScore;
            if (workQualification.getType1ID() == 1) { // 著作类（学术专著、工具书等）
                Float wordsNum = workQualification.getWordsNum();
                if (Objects.isNull(wordsNum) || wordsNum <= 0) {
                    throw new BaseException("著作类需填写字数（万字）!");
                }
                // 字数截断（学术专著≤40万，其他≤30万）
                float truncatedWords = (workQualification.getType2ID() == 1) ?
                        Math.min(wordsNum, 40) : Math.min(wordsNum, 30);
                baseScore = truncatedWords * 5 * workType.getValue() * workPress.getPressValue();
            } else { // 创作类（音乐、美术等）
                Float facesNum = workQualification.getFacesNum();
                if (Objects.isNull(facesNum) || facesNum <= 0) {
                    throw new BaseException("创作类需填写面数!");
                }
                baseScore = facesNum * 0.6 * workType.getValue() * workPress.getPressValue();
            }

            finalScore = baseScore;
        }



        // 9. 数据入库
        workQualification.setFinalValue((float) finalScore);
        workDTO.setScore((float) finalScore);
        Work workEntity = new Work();
        BeanUtils.copyProperties(workDTO, workEntity);
        iWorkService.updatework(workEntity);

        String Pscore = "0.00";
        // 9. 修改著作作者的个人得分
        String workid=workQualification.getWorkID();
        List<Workauthor> workauthorList = iWorkauthorService.pageworkauthor(workid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (workauthorList != null && !workauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (workauthorList.size() == 1) {
                Workauthor soleAuthor = workauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Workauthor author : workauthorList) {
                    iWorkauthorService.updateWorkAuthor(author);
                }
            }
        }

        return baseMapper.insert(workQualification) > 0;
    }

    /**
     * 删除量化分数
     * @param workQuantificationID
     * @return
     */
    @Override
    public boolean deleteWork_Qualification(String workQuantificationID) {

        Work_Qualification existEntity = baseMapper.selectById(workQuantificationID);
        if (Objects.isNull(existEntity)) {
            throw new BaseException("量化数据不存在!");
        }

        Work work = iWorkService.getWork(existEntity.getWorkID());
        checkRoleUtil.checkPermissionProject(work.getStatus()); // 权限校验

        // 清空Work表分数
        WorkDTO workDTO = iWorkService.getWorkDTOById(existEntity.getWorkID());
        workDTO.setScore(0.0F);

        Work workEntity = new Work();
        BeanUtils.copyProperties(workDTO, workEntity);
        iWorkService.updatework(workEntity);

        List<Workauthor> workauthorList = iWorkauthorService.pageworkauthor(existEntity.getWorkID());
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (workauthorList != null && !workauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (workauthorList.size() == 1) {
                Workauthor soleAuthor = workauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Workauthor author : workauthorList) {
                    iWorkauthorService.updateWorkAuthor(author);
                }
            }
        }


        return baseMapper.deleteById(workQuantificationID) > 0;

    }


    @Override
    public List<Work_Qualification> getOneWork_Qualification(String WorkID) {
        Work work = iWorkService.getWork(WorkID);
        if(Objects.isNull(work)){
            throw new BaseException("著作编号有误!");
        }

        List<Work_Qualification> work_qualifications = baseMapper.selectList(Wrappers.lambdaQuery(Work_Qualification.class)
                .eq(Work_Qualification::getWorkID, WorkID));

        return work_qualifications;

    }

    /**
     * 校级管理员修改作品分数
     * @param workQualification
     * @return
     */
    @Override
    public boolean upWorkScore(Work_Qualification workQualification){

        Work_Qualification existEntity = baseMapper.selectById(workQualification);;
        if (Objects.isNull(existEntity)) {
            throw new BaseException("量化数据不存在!");
        }

        Work work = iWorkService.getWork(existEntity.getWorkID());
        checkRoleUtil.checkPermissionProject(work.getStatus());

        // 仅更新分值，类型不可变
        existEntity.setFinalValue(workQualification.getFinalValue());
        baseMapper.updateById(existEntity);


        // 同步更新Work表
        WorkDTO workDTO = iWorkService.getWorkDTOById(existEntity.getWorkID());
        workDTO.setScore(existEntity.getFinalValue());


        Work workEntity = new Work();
        BeanUtils.copyProperties(workDTO, workEntity);
        iWorkService.updatework(workEntity);

        String Pscore = "0.00";
        String workid=workQualification.getWorkID();
        List<Workauthor> workauthorList = iWorkauthorService.pageworkauthor(workid);
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        if (workauthorList != null && !workauthorList.isEmpty()) {
            boolean shouldUpdate = true;
            if (workauthorList.size() == 1) {
                Workauthor soleAuthor = workauthorList.get(0);
                if (Objects.equals(soleAuthor.getUserAccount(), user.getAccount())) {
                    shouldUpdate= false;
                }
            }
            // 执行更新操作
            if (shouldUpdate) {
                for (Workauthor author : workauthorList) {
                    iWorkauthorService.updateWorkAuthor(author);
                }
            }
        }

        return true;
    }



    /**
     * 检查是否已存在量化数据
     */
    private boolean existQuantification(String workID) {
        return baseMapper.selectCount(Wrappers.lambdaQuery(Work_Qualification.class)
                .eq(Work_Qualification::getWorkID, workID)) > 0;
    }
    @Override
    public Work_Qualification getById(String id){
        Work_Qualification work_qualification = baseMapper.selectOne(Wrappers.lambdaQuery(Work_Qualification.class)
                .eq(Work_Qualification::getWorkID, id));
        return work_qualification;
    }

}
